import * as mutations from './mutation-types'
import envFuncs from '@/config/base'
let env = envFuncs.getParams()
import jsapi from '../lib/ddApiConfig'
import {getRequestId, S, U, mapField} from '../lib/backend'
import axios from 'axios'
import Q from 'q'

export default {
  getRequestAuthCode ({dispatch, state}, corpId) {
    if (
      !window.ability ||
      window.ability < jsapi['runtime.permission.requestAuthCode']
    ) {
      console.warn('容器版本过低，不支持 runtime.permission.requestAuthCode')
      return
    }

    dd.runtime.permission.requestAuthCode({
      corpId: state.app.ddConfig.corpId || corpId,
      onSuccess: function (result) {
        dispatch(mutations.UPDATE_CODE, result.code)

        getUserInfo({dispatch, state}, result.code)

        console.log('获取到了免登陆code=>' + result.code)
      },
      onFail: function (err) {
        dispatch(mutations.UPDATE_CODE, false)
        console.log('获取免登陆code失败')
      }
    })
  },
  updateFilterOptions ({commit, state}, options) {
    commit('UPDATE_FILTER_OPTIONS', options)
  },
  // getUserInfo({dispatch, state}, code) {
  //   axios.get(env.API_HOST+'/user/getUserinfo', {
  //     params: {
  //       code: code,
  //       corpId: state.app.ddConfig.corpId,
  //       suiteKey: window.getParamByName('suiteKey')
  //     },
  //     timeout: 5000,
  //   }).then(function (response) {
  //     if(response.status == 200 && response.data.code == 200){
  //       let user = response.data.result
  //       dispatch(mutations.LOGIN_SUCCESS, user);
  //       dispatch(mutations.UPDATE_SYS_LEVEL, user.sys_level);
  //     }else{
  //       dispatch(mutations.LOGIN_ERROR,false)
  //     }
  //   }).catch(function (err) {
  //     dispatch(mutations.LOGIN_ERROR,false)
  //   });
  // },

  Login ({commit, state}, requestId, code) {
    return axios
      .post(
        env.CRM_API_HOST + '/ding/login' + '?' + U(),
        S({
          params: {
            trace: {
              requestId: requestId
            },
            info: {
              code: code
            }
          },
          timeout: 5000
        })
      )
      .then(function (response) {
        if (response.data.errcode === 0) {
          let token = response.token
          commit(mutations.UPDATE_TOKEN, token)
        } else {
          commit(mutations.LOGIN_ERROR, false)
        }
      })
      .catch(function (err) {
        commit(mutations.LOGIN_ERROR, false)
        console.log(err)
      })
  },

  // 获取用户信息
  getUserInfo ({dispatch, commit, state}) {
    if (!state.token) {
      dispatch('Login').then(() => {
        dispatch('getUserInfo')
      })
    } else {
      let params = U({})
      console.debug('getUserInfo', params)
      axios
        .get(env.CRM_API_HOST + '/users/' + state.token + '?' + params)
        .then(function (response) {
          commit(mutations.UPDATE_USER, response.data.results)
        })
    }
  },

  // 获取工作台信息
  saveWorckbenchInfo ({dispatch, commit, state}, info) {
    let params = S({
      trace: {requestId: getRequestId()},
      achievement: info
    })
    console.log(params)
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/achievements' + '?' + U(),
      params
    )
  },

  getWorckbenchInfo ({dispatch, commit, state}, info) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/index?' + U(info)
    )
  },

  getOrders({dispatch, commit, state}, info) {
    return axios.get(
      env.CRM_API_HOST + '/orders?' + U(info)
    )
  },

  getClueAssist({dispatch, commit, state}, info) {
    return axios.get(
      env.CRM_API_HOST+ '/users/' + state.token + '/clue_assist?' + U(info)
    )
  },

  saveOrderStatus({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/achievements/sales/' + info + '/cancel'
    )
  },


  getAchievementsInfo ({dispatch, commit, state}, info) {
    console.debug('info', info)

    return axios.get(
      env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/achievements/' +
        info.year +
        '?' +
        U(info)
    )
  },

  // 查询客户信息列表接口，包括社交客户和我的客户
  getCustoms ({dispatch, commit, state}, data) {
    let params = U(data)
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/customs?' + params
    )
  },
  // 查重接口
  getAllCustoms ({dispatch, commit, state}, data) {
    let params = U(data)
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/allcustoms?' + params
    )
  },
  getSubscribeClients ({dispatch, commit, state}, data) {
    let params = U(data)
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/new_customs/' + data.batch_no + '?' + params
    )
  },

  getActivities ({dispatch, commit, state}, data) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/h5' + '?' + U()
    )
  },

  // 查询客户公海信息列表接口，包括社交客户和我的客户
  getClientSeasCustoms ({dispatch, commit, state}, data) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/gonghai?' + U(data)
    )
  },

  // 查询详情信息，包括社交客户和我的客户
  getCustomInfoById ({dispatch, commit, state}, id) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/customs/' + id + '?' + U()
    )
  },

  // 管理客户信息接口
  saveClientInfo ({dispatch, commit, state}, info) {
    let id = ''
    let url = ''
    if (typeof info.id !== 'undefined') {
      id = info.id
      delete info.id
      url = env.CRM_API_HOST + '/users/' + state.token + '/customs/' + id
    } else {
      url = env.CRM_API_HOST + '/users/' + state.token + '/customs'
    }
    return axios.post(
      url,
      S({
        trace: {requestId: getRequestId()},
        info: info
      })
    )
  },

  // 查询客户宝宝列表接口
  getBabys ({dispatch, commit, state}, id) {
    return axios.get(
      env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/customs/' +
        id +
        '/babys' +
        '?' +
        U()
    )
  },

  // 管理客户宝宝接口
  saveBabys ({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/customs/' +
        info.id +
        '/babys' +
        '?' +
        U(),
      S({
        trace: {requestId: getRequestId()},
        info: info.info
      })
    )
  },

  // 查询线索列表
  getClues ({dispatch, commit, state}, data) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/clues?' + U(data)
    )
  },

  // 保存线索列表
  saveClues ({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/clues' + '?' + U(),
      S({
        trace: {requestId: getRequestId()},
        info: info
      })
    )
  },

  // 下发h5
  sendH5 ({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/sendh5' + '?' + U(),
      S({
        trace: {requestId: getRequestId()},
        info: info
      })
    )
  },

  // 下发h5
  sendCard ({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/send_card' + '?' + U(),
      S({
        trace: {requestId: getRequestId()},
        info: info
      })
    )
  },

  // 新增预约试听信息
  saveAppointments ({dispatch, commit, state}, info) {
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/appointments' + '?' + U(),
      S({
        trace: {requestId: getRequestId()},
        info: info
      })
    )
  },
  getAppointments ({dispatch, commit, state}, id) {
    let CRM_API_HOST = env.CRM_API_HOST
    // CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    return axios.get(
      CRM_API_HOST + '/users/' + state.token + '/appointments/' + id + '?' + U())
  },

  // 获取扫码详情
  getScanCodeDetail ({dispatch, commit, state}, id) {
    let CRM_API_HOST = env.CRM_API_HOST
    // CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    return axios.get(
      CRM_API_HOST + '/users/' + state.token + '/page_evevt/' + id + '?' + U())
  },

  // 查询团队列表
  getTeams ({dispatch, commit, state}, data) {
    let args = U(Object.assign({source: 'webapp'}, data));
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/teams?' + args
    )
  },

  // 保存团队
  saveTeams ({dispatch, commit, state}, info) {
    let params = ''
    if (typeof info.id !== 'undefined') {
      params = '/' + info.id
    }

    return axios.post(
      env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/teams' +
        params +
        '?' +
        U(),
      S({
        trace: {
          requestId: getRequestId()
        },
        info: info
      })
    )
  },

  // 查询团队
  getTeam ({dispatch, commit, state}, teamId) {
    return axios.get(
      env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/teams/' +
        teamId +
        '?' +
        U()
    )
  },

  // 名片信息查询接口
  getCard ({dispatch, commit, state}) {
    return axios.get(
      env.CRM_API_HOST + '/users/' + state.token + '/card' + '?' + U()
    )
  },

  // 名片信息查询接口
  getDictionary ({dispatch, commit, state}, code) {
    let params = ''
    if (code) {
      params = '/' + code
    }
    let url = env.CRM_API_HOST + '/data_dictionary' + params + '?' + U()
    return axios.get(url)
  },

  // 获取我的海报列表
  getPosters ({dispatch, commit, state}, info) {
    // env.CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    let url = env.CRM_API_HOST + '/users/' + state.token + '/poster' + '?' + U(info)
    return axios.get(url)
  },

  getCustomSource ({dispatch, commit, state}) {
    return dispatch('getDictionary', 'custom_source').then((response) => {
      commit('UPDATE_CUSTOM_SOURCES', response.data.results)
    })
  },
  getChannel ({dispatch, commit, state}) {
    return dispatch('getDictionary', 'channel').then((response) => {
      commit('UPDATE_CHANNEL', response.data.results)
    })
  },

  // 名片信息保存接口
  saveCard ({dispatch, commit, state}, info) {
    let data = Object.assign({trace: {requestId: getRequestId()}}, info)

    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/card' + '?' + U(),
      S(data)
    )
  },

  // 解绑海报
  unBindPoster ({dispatch, commit, state}, id) {
    // env.CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    return axios.delete(
      env.CRM_API_HOST + '/users/' + state.token + '/poster/' + id + '?' + U()
    )
  },

  // 解绑海报
  bindPoster ({dispatch, commit, state}, info) {
    // env.CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    let data = Object.assign({trace: {requestId: getRequestId()}}, info)
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/poster' + '?' + U(),
      S(data)
    )
  },
  verificationCode ({dispatch, commit, state}, info) {
    // env.CRM_API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/18476'
    let data = Object.assign({trace: {requestId: getRequestId()}}, info)
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/verification' + '?' + U(),
      S(data)
    )
  },

  // 客户调配
  distribute ({dispatch, commit, state}, info) {
    let data = Object.assign({trace: {requestId: getRequestId()}}, info)
    return axios.post(
      env.CRM_API_HOST + '/users/' + state.token + '/distribute' + '?' + U(),
      S(data)
    )
  },
  // 根据指定id列表获取客户详情
  queryCustomsByIds ({dispatch, commit, state}, list) {
    return axios.post(
      env.CRM_API_HOST +
        '/users/' + state.token + '/customs/list' + '?' + U(),
        S({
          info: {
            id_list: list
          }
        })
    )
  },
  updateSourceFilter ({dispatch, commit, state}) {
    commit(mutations.UPDATE_SOURCE_FILTER, 1)
  },
  updateChannelFilter ({dispatch, commit, state}) {
    commit(mutations.UPDATE_CHANNEL_FILTER, 1)
  },
  updateLocation ({dispatch, commit, state}, location) {
    commit(mutations.UPDATE_LOCATION, location)
  },
  //获取市场 人员名单
  getMarketerList ({dispatch, commit, state}) {
    return axios.get(
        env.CRM_API_HOST + '/users/' + state.token + '/get/marketer/list' + '?' + U()
    )
  },
  // 删除市场 人员
  delMarketer ({dispatch, commit, state}, info) {
    let params = ''
    if (typeof info.id !== 'undefined') {
      params = '/' + info.id
    }
    return axios.post(
        env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/del/marketer' +
        params +
        '?' +
        U(),
        S({
          trace: {
            requestId: getRequestId()
          },
          info: info
        })
    )
  },
  //保存市场人员
  saveMarketer ({dispatch, commit, state}, info) {
    return axios.post(
        env.CRM_API_HOST +
        '/users/' +
        state.token +
        '/marketer' +
        '?' +
        U(),
        S({
          trace: {
            requestId: getRequestId()
          },
          info: info
        })
    )
  },
}
